import 'package:flutter_admin/api/odoo/res_partner_odoo_api.dart';
import 'package:flutter_admin/models/odoo/res_partner.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';

class SaleInquiryPartnerList extends StatefulWidget {
  String? partnerTitle;

  SaleInquiryPartnerList({Key? key, this.partnerTitle}) : super(key: key);
  @override
  _SaleInquiryPartnerListState createState() => _SaleInquiryPartnerListState();
}

class _SaleInquiryPartnerListState extends State<SaleInquiryPartnerList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  ResPartner resPartner = ResPartner();
  List<ResPartner> selectedList = [];
  bool flag = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '客户名称',
            value: resPartner.name,
            onSaved: (v) {
              resPartner.name = v;
            },
          ),
        ],
      ),
    );
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        if (flag) {
          Navigator.pop(context, selected);
        }
        flag = false;
      },
      columns: [
        DataColumn(
          label: Text('客户性质'),
        ),
        DataColumn(
          label: Text('客户名称'),
        ),
        DataColumn(
          label: Text('邮编'),
        ),
        DataColumn(
          label: Text('区域'),
        ),
        DataColumn(
          label: Text('国家'),
        ),
        DataColumn(
          label: Text('城市'),
        ),
        DataColumn(
          label: Text('地址'),
        ),
        DataColumn(
          label: Text('主页'),
        ),
        DataColumn(
          label: Text('客户等级'),
        ),
        DataColumn(
          label: Text('客户状态'),
        ),
        DataColumn(
          label: Text('客户类型'),
        ),
        DataColumn(
          label: Text('客户来源'),
        ),
        DataColumn(
          label: Text('行业类型'),
        ),
        DataColumn(
          label: Text('信用等级'),
        ),
        DataColumn(
          label: Text('业务经理(中天)'),
        ),
      ],
      getCells: (m) {
        ResPartner resPartner = ResPartner.fromMap(m);
        return [
          DataCell(Text(resPartner.customerNature ?? '--')),
          DataCell(Text(resPartner.name ?? '--')),
          DataCell(Text(resPartner.zip ?? '--')),
          DataCell(Text(resPartner.area ?? '--')),
          DataCell(Text(resPartner.countryId ?? '--')),
          DataCell(Text(resPartner.city ?? '--')),
          DataCell(Text(resPartner.contactAddress ?? '--')),
          DataCell(Text(resPartner.website ?? '--')),
          DataCell(Text(resPartner.customerLevel ?? '--')),
          DataCell(Text(resPartner.customerState ?? '--')),
          DataCell(Text(resPartner.customerType ?? '--')),
          DataCell(Text(resPartner.customerSource ?? '--')),
          DataCell(Text(resPartner.industryId ?? '--')),
          DataCell(Text(resPartner.creditRating ?? '--')),
          DataCell(Text(resPartner.userId ?? '--')),
        ];
      },
    );
    _getSelectList();

    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title:
            Text(widget.partnerTitle != null ? widget.partnerTitle! : '客户档案'),
      ),
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          form,
          buttonBar,
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    resPartner = ResPartner();
    formKey.currentState!.reset();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await ResPartnerOdooApi.page(
        data: {"page": page, "domainList": resPartner.toDomainList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<ResPartner>((e) => ResPartner.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }
}
